package com.rh.redis.controller;

import com.rh.entity.user.RenHaiUser;
import com.rh.redis.redieserver.RedisService;
import com.rh.redis.token.JavaWebToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import renhai.util.CodeUtil;
import renhai.util.Constant;
import renhai.util.ResponseContext;

import java.util.Map;

/**
 * @author 57556
 */
@RestController
@RequestMapping("/api/redis")
public class RedisController {
    @Autowired
    private RedisService service;
    @Value("${token.time}")
    private Integer tokenTime;

    @PostMapping("saveToken")
    public ResponseContext<String> saveToken(@RequestBody RenHaiUser user) {
        //生成token
        String token = JavaWebToken.createJavaWebToken(user.getUserId());
        //写入redis 设置过期时间毫秒
        service.set(token, user, tokenTime);
        ResponseContext<String> responseContext = new ResponseContext<>();
        responseContext.setEntity(token);
        return responseContext;
    }

    /**
     * 配置缓存
     */
    @PostMapping("set")
    public ResponseContext<String> set(@RequestBody Map<String, String> map) {
        service.set(map.get("key"), map.get("value"), Integer.parseInt(map.get("value")));
        return Constant.SAVE_S;
    }

    @PostMapping("get")
    public ResponseContext<String> get(@RequestBody Map<String, String> map) {

        return new ResponseContext<>(service.get(map.get("key"), String.class), "get");
    }

    @PostMapping("remove")
    public ResponseContext<String> remove(@RequestBody Map<String, String> map) {
        service.remove(map.get("key"));
        return new ResponseContext<>("remove");
    }

    @PostMapping("clear")
    public ResponseContext<String> clear() {
        service.clear();
        return new ResponseContext<>("remove");
    }

    @PostMapping("getSize")
    public ResponseContext<Integer> getSize() {

        return new ResponseContext<>(service.getSize(), "getSize");
    }

    /**
     * 检查用户是否登陆
     */
    @PostMapping("checkToken")
    public ResponseContext<String> checkToken(@RequestBody Map<String, String> map) {
        String key = map.get("key");
        if (service.hasKey(key)) {
            //查看是否过期
            Long time = service.getExpire(key);
            if (time != -1) {
                service.expire(key, tokenTime);
                return new ResponseContext<>("更新过期时间", 1);
            } else {
                return new ResponseContext<>("登陆过期", 0, CodeUtil.PAST_DU_LOG);
            }
        } else {
            return new ResponseContext<>("未登录", 0, CodeUtil.NOT_LOG);
        }
    }


}
